import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    //component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  },
  {
    path: '/home',
    name: 'Home',
    component:()=>import('../components/Home.vue'),
    redirect: '/welcome',
    children: [
      //欢迎子组件
      {
        path: '/welcome',
        name: 'Welcome',
        component:()=>import('../views/Welcome.vue')
      },
      //用户列表子组件
      {
        path:'/users',
        name: 'User',
        component:()=>import('../views/user/User.vue')
      },
      //权限管理-角色列表
      {
        path:'/roles',
        name: 'Roles',
        component:()=>import('../views/power/Roles.vue')
      },
      //权限管理-权限列表
      {
        path:'/rights',
        name: 'rights',
        component:()=>import('../views/power/Right.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

//为路由对象，添加 beforeEach导航守卫
router.beforeEach((to,from,next)=>{
  //如果有页面访问登录页，直接放行
  if(to.path==='/login') return next()
  const tokenStr = window.sessionStorage.getItem('token')
  //如果没有token的路由，强制跳转到登录页
  if(!tokenStr) return next('/login')
  next()
})

export default router
